<template>
  <BasicModal
    :width="540"
    :minHeight="260"
    v-bind="$attrs"
    @register="register"
    title="单位设置"
    @ok="onSave"
    okText="保存"
    :showOkBtn="true"
    :showCancelBtn="true"
    :canFullscreen="false"
    :maskClosable="false"
    :centered="true"
    :destroyOnClose="true"
  >
    <div class="card">
      <div class="c-title">产品单位</div>
      <BasicForm @register="registerForm1" class="form" />
    </div>

    <div class="card">
      <div class="c-title">换算单位</div>
      <BasicForm @register="registerForm2" class="form" />
    </div>
  </BasicModal>
</template>
<script>
  import { defineComponent, nextTick, reactive, ref, toRefs } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { proCsmUnit, proSaleUnit } from '@/api/ds';

  export default defineComponent({
    name: 'UnitDialog',
    components: {
      BasicModal,
      BasicForm,
    },
    emits: ['complete'],
    setup(props, { emit }) {
      const state = reactive({
        behavior: '',
      });

      const recordRef = ref({});

      const [registerForm1, form1] = useForm({
        labelWidth: 130,
        labelAlign: 'left',
        baseColProps: { span: 24, style: { paddingRight: '36px' } },

        schemas: getSchema1(),
        showActionButtonGroup: false,
      });

      const [registerForm2, form2] = useForm({
        labelWidth: 130,
        labelAlign: 'left',
        baseColProps: { span: 24, style: { paddingRight: '36px' } },

        schemas: getSchema2(),
        showActionButtonGroup: false,
      });

      function getSchema1() {
        return [
          {
            label: '售卖单位',
            field: 'saleUnit',
            required: true,
            component: 'Select',
            componentProps: {
              options: proSaleUnit,
              onChange: () => {
                nextTick(updateSchema2);
              },
            },
          },

          {
            label: '消耗单位',
            field: 'csmUnit',
            required: true,
            component: 'Select',
            componentProps: {
              options: proCsmUnit,
              onChange: () => {
                nextTick(updateSchema2);
              },
            },
          },
        ];
      }

      function getSchema2() {
        const { saleUnit, csmUnit } = form1?.getFieldsValue() ?? {};

        return [
          {
            label: '售卖&消耗单位',
            field: 'saleToCsm',
            required: true,
            component: 'InputNumber',
            componentProps: {
              min: 0,
              max: 9999999,
              precision: 0,
              addonBefore: `每${saleUnit || ''}含`,
              addonAfter: csmUnit || '',
            },
          },
        ];
      }

      const formList = [form1, form2];

      async function updateSchema2() {
        await form2.setProps({ schemas: getSchema2() });

        formList.forEach((f) => {
          try {
            f.clearValidate();
          } catch (e) {
            //
          }
        });
      }

      const [register, { closeModal }] = useModalInner(async ({ behavior, record }) => {
        state.behavior = behavior;

        record ||= {};
        recordRef.value = record;

        //初始化表单
        const initData = {};
        Object.assign(initData, recordRef.value);

        formList.forEach((f) => {
          f.setFieldsValue(initData);
        });

        await updateSchema2();
      });

      async function onSave() {
        await Promise.all(formList.map((f) => f.validate()));
        const formData = formList.reduce((prev, f) => Object.assign(prev, f.getFieldsValue()), {});

        emit('complete', formData);
        closeModal();
      }

      return {
        ...toRefs(state),
        register,
        onSave,
        registerForm1,
        registerForm2,
      };
    },
  });
</script>
<style lang="less" scoped>
  .card {
    margin: 0 16px 0px 8px;
    padding: 0 16px 0px 16px;
    background-color: #fff;

    .c-title {
      display: flex;
      flex-direction: row;
      align-items: center;
      margin-bottom: 18px;
      column-gap: 8px;
      color: #091f3d;
      font-size: 14px;
      font-weight: 600;
    }

    .form {
      padding: 0 12px 0 0;
    }
  }
</style>
